#ifndef __CHATSERVICE_H__
#define __CHATSERVICE_H__

#include "json.hpp"

#include <unordered_map>
#include <functional>
#include <muduo/net/TcpConnection.h>
#include <muduo/base/Timestamp.h>
#include <mutex>
#include "usermodel.hpp"
#include "offlinemsgmodel.hpp"
#include "friendmodel.hpp"
#include "groupmodel.hpp"

using json = nlohmann::json;

using MsgHandler = std::function<void(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time)>;

class ChatService
{
public:
    static ChatService* instance();
    void login(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    void reg(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    void oneChat(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    void addFriend(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    void createGroup(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    void addGroup(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    void groupChat(const muduo::net::TcpConnectionPtr&, json &js, muduo::Timestamp time);
    MsgHandler getHangler(int msgid);
    void clientCloseExecption(const muduo::net::TcpConnectionPtr &conn);
    void reset();
private:
    ChatService();
    std::unordered_map<int, MsgHandler> msgHandlerMap_;
    std::unordered_map<int, muduo::net::TcpConnectionPtr> userConnMap_;
    std::mutex connMutex_;
    UserModel userModel_;
    OfflineMsgModel offlineMsgModel_;
    FriendModel friendModel_;
    GroupModel groupModel_;
};

#endif